package com.yyjj.yyjj.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.yyjj.yyjj.common.auth.AuthContextHolder;
import com.yyjj.yyjj.common.constant.RedisConst;
import com.yyjj.yyjj.common.exception.YYJJException;
import com.yyjj.yyjj.common.result.Result;
import com.yyjj.yyjj.common.result.ResultCodeEnum;
import com.yyjj.yyjj.common.utils.JwtHelper;
import com.yyjj.yyjj.enums.UserType;
import com.yyjj.yyjj.model.user.User;
import com.yyjj.yyjj.user.service.UserService;
import com.yyjj.yyjj.user.utils.ConstantPropertiesUtil;
import com.yyjj.yyjj.user.utils.HttpClientUtils;
import com.yyjj.yyjj.vo.user.LeaderAddressVo;
import com.yyjj.yyjj.vo.user.UserLoginVo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/weixin")
@RequiredArgsConstructor
public class WeixinApiController {

    private final UserService userService;

    private final RedisTemplate redisTemplate;

    @ApiOperation(value = "微信登录获取openid(小程序)")
    @GetMapping("/wxLogin/{code}")
    public Result callback(@PathVariable String code) {
        //获取授权临时票据
        //2拿着code+小程序id+小程序秘钥请求微信接口服务
        //使用HttpClient工具请求
        String wxOpenAppId = ConstantPropertiesUtil.WX_OPEN_APP_ID;
        String wxOpenAppSecret = ConstantPropertiesUtil.WX_OPEN_APP_SECRET;
        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String tokenUrl = String.format(url.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        try {
            result = HttpClientUtils.get(tokenUrl);
        } catch (Exception e) {
            throw new YYJJException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }
        //3请求微信接口服务，返回两个值session key和openId
        //openId,是你微信唯一标识
        JSONObject jsonObject = JSONObject.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openId");
        //4添加微信用户信息到数据库里面
        ///操作user表
        ////判断是否是第一次使用微信授权登录：如何判断？openId
        User user = userService.getUserByOpenId(openId);
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            user.setNickName(openId);
            user.setPhotoUrl("");
            user.setUserType(UserType.USER);
            user.setIsNew(0);
            userService.save(user);
        }
        //5根据userId.查询提货点和团长信息
        ///提货点
        ///团长
        LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId());
        //6使用JWT工具根据userId和serName生成token字符串
        String token = JwtHelper.createToken(user.getId(), user.getNickName());
        //7获取当前登录用户信息，放到Redis里面，设置有效时间
        UserLoginVo userLoginVo = userService.getUserLoginVo(user.getId());
        redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + user.getId(), userLoginVo, RedisConst.USERKEY_TIMEOUT, TimeUnit.DAYS);
        //8需要数据封装到map返回
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", token);
        map.put("leaderAddressVo", leaderAddressVo);
        return Result.ok(map);
    }

    @PostMapping("/auth/updateUser")
    @ApiOperation(value = "更新用户昵称与头像")
    public Result updateUser(@RequestBody User user) {
        User user1 = userService.getById(AuthContextHolder.getUserId());
        //把昵称更新为微信用户
        user1.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
        user1.setPhotoUrl(user.getPhotoUrl());
        userService.updateById(user1);
        return Result.ok(null);
    }
}